<?php

class Inbound_IndexController extends Zend_Controller_Action
{
	protected $_object;
	public $string_inbound_type;
	public $string_inbound_type_2;
	public $string_report_type;
	public $inbound_type;
	public $inbound_warehouse_group_code;
	public $string_warehouse_group_name;

	//init
	public function init()
	{
		//tạo đối tượng chính của module
		$this->_object = new Admin_Model_Inbound ();
	}

	protected function _setInboundString($inbound_warehouse_group_code, $inbound_type)
	{
		//lấy tên nhóm kho
		switch ($inbound_warehouse_group_code)
		{
			case 'NVL' :
				//$this->string_warehouse_group_name = 'nguyên vật liệu';
				$this->string_warehouse_group_name = 'sản phẩm';
				break;
			case 'BB' :
				$this->string_warehouse_group_name = 'bao bì';
				break;
			case 'TP' :
				$this->string_warehouse_group_name = 'thành phẩm';
				break;
		}
		
		//thay thế ngôn ngữ ứng với loại phiếu nhập, phiếu xuất riêng
		$array_replace_caption = array ();
		if ($inbound_type == 1)
		{
			$this->string_inbound_type_2 = $array_replace_caption ['string_inbound_type_2'] = 'nhận';
			$this->string_inbound_type = $array_replace_caption ['string_inbound_type'] = 'xuất';
		}
		else
		{
			$this->string_inbound_type_2 = $array_replace_caption ['string_inbound_type_2'] = 'giao';
			$this->string_inbound_type = $array_replace_caption ['string_inbound_type'] = 'nhập';
		}
		
		//gan 2 tham so chinh
		$this->inbound_warehouse_group_code = $inbound_warehouse_group_code;
		$this->inbound_type = $inbound_type;
		
		//lấy tiêu đề 
		$this->_helper->common->setCaptions ( $array_replace_caption, array ("inbound", "inbound-detail", "inventory" ) );
		
		//truyền dữ liệu ra view
		$this->view->string_warehouse_group_name = $this->string_warehouse_group_name;
		$this->view->string_inbound_type_2 = $this->string_inbound_type_2;
		$this->view->string_inbound_type = $this->string_inbound_type;
		$this->view->inbound_type = $this->inbound_type;
		$this->view->inbound_warehouse_group_code = $this->inbound_warehouse_group_code;
	}

	//tính năng copy 1 phiếu ra phiếu mới
	protected function copyAction()
	{
		//lấy tham số
		$request = $this->_request;
		$id = $request->getParam ( 'id' );
		$tmp = $request->getParam ( 'tmp', '' );
		
		//lấy dữ liệu phiếu cũ
		if ($tmp == '1') //Truong hop la phieu tam
		{
			$first_inbound = new Admin_Model_TmpInbound ();
			$first_inbound->findBase ( $id )->setInbound_status ( 1 )->updateBase ();
		}
		else //Truong hop la phieu chinh
		{
			$first_inbound = new Admin_Model_Inbound ();
			$first_inbound->findBase ( $id );
		}
		
		$array_data = array ("inbound_warehouse_code" => $first_inbound->inbound_warehouse_code, "inbound_warehouse_keep_user" => $first_inbound->inbound_warehouse_keep_user, "inbound_reason_code" => $first_inbound->inbound_reason_code, "inbound_note" => $first_inbound->inbound_note, "inbound_company_code" => $first_inbound->inbound_company_code, "inbound_delivery_user" => $first_inbound->inbound_delivery_user, "inbound_type" => $first_inbound->inbound_type, "inbound_warehouse_group_code" => $first_inbound->inbound_warehouse_group_code );
		
		//lấy dữ liệu chi tiet của phiếu cũ
		if ($tmp == '1') //Truong hop la phieu tam
		{
			$inbound_detail = new Admin_Model_TmpInboundDetail ();
			$inbound_details = $inbound_detail->fetchAllBase ( "inbound_detail_inbound_code='$first_inbound->inbound_code'" );
			if (count ( $inbound_details ) == 1)
			{
				$inbound_detail = new Admin_Model_TmpInboundDetail ();
				$inbound_details [] = $inbound_detail;
			}
			foreach ( $inbound_details as $inbound_detail )
			{
				$array_data ['inbound_detail_product_code'] [] = $inbound_detail->inbound_detail_product_code;
				$array_data ['inbound_detail_product_unit_code'] [] = $inbound_detail->inbound_detail_product_unit_code;
				$array_data ['inbound_detail_product_quantity'] [] = $inbound_detail->inbound_detail_product_quantity;
				$array_data ['inbound_detail_note'] [] = $inbound_detail->inbound_detail_note;
			}
		}
		
		//chuyển hướng qua trang insert
		$this->_helper->flashMessenger ( "Copy phiếu mới từ phiếu {$first_inbound->inbound_code} thành công" );
		if ($first_inbound->inbound_type == 1)
			$this->_helper->redirector ( "insert-out", "index", "inbound", $array_data );
		else
			$this->_helper->redirector ( "insert-in", "index", "inbound", $array_data );
	}

	//xem danh sách tất cả 
	public function indexAction()
	{
		//lấy tham số
		$request = $this->_request;
		$adminAction = $request->getParam ( 'adminAction', '' );
		$layout = $request->getParam ( 'layout', '' );
		$inbound_code = $request->getParam ( 'inbound_code', '' );
		$report_type = $request->getParam ( 'report_type', 0 ); //loại báo cáo.0:chung,1:chi tiet
		$inbound_name = $request->getParam ( 'inbound_name', '' );
		$inbound_company_code = $request->getParam ( 'inbound_company_code', '' );
		$inbound_create_user = $request->getParam ( 'inbound_create_user', '' );
		$inbound_warehouse_code = $request->getParam ( 'inbound_warehouse_code', '' );
		$inbound_reason_code = $request->getParam ( 'inbound_reason_code', '' );
		$inbound_create_time_a = $request->getParam ( 'inbound_create_time_a', '' );
		$inbound_create_time_b = $request->getParam ( 'inbound_create_time_b', '' );
		$inbound_detail_product_code = $request->getParam ( 'inbound_detail_product_code', '' );
		$inbound_detail_sub_product_code = $request->getParam ( 'inbound_detail_sub_product_code', '' );
		$product_group_code = $request->getParam ( 'product_group_code', '' );
		
		//layout
		if ($layout != '')
			$this->getHelper ( 'Layout' )->setLayout ( $layout );
		
		//set tham số
		$this->_setInboundString ( $request->getParam ( 'inbound_warehouse_group_code' ), $request->getParam ( 'inbound_type' ) );
		
		//tạo form
		$form = new Inbound_Form_Inbound_Search ( $this );
		
		//Lay danh sach ma phieu
		$inbounds = $this->_object->fetchAllBase ( "inbound_type = '{$this->inbound_type}' AND inbound_warehouse_group_code = '{$this->inbound_warehouse_group_code}'" );
		$form->inbound_code->fillSource ( array ('i_source' => $inbounds, 'i_condition' => '$row->inbound_code' ) );
		
		//select kho nhập hàng
		$warehouse = new Admin_Model_Warehouse ();
		$warehouses = $warehouse->fetchAllBase ( NULL, 'warehouse_name ASC' );
		$warehouses = $warehouse->toArray2 ( $warehouses, 'warehouse_code', '$row->warehouse_code - $row->warehouse_name' );
		$form->inbound_warehouse_code->setMultiOptions ( array ('' => '- Chọn -' ) + $warehouses );
		
		//Lay thong tin nguoi tao phieu
		$account = new Admin_Model_Account ();
		$accounts = $account->fetchAllBase ( NULL, 'account_username ASC' );
		$accounts = $account->toArray2 ( $accounts, 'account_username', '$row->account_username - $row->account_fullname' );
		$form->inbound_create_user->setMultiOptions ( array ('' => '- Chọn -' ) + $accounts );
		
		//Lay thong tin ncc, khach hàng
		if ($this->inbound_type == '0')
		{
			$supplier = new Admin_Model_Supplier ();
			$suppliers = $supplier->fetchAllBase (null,"supplier_code ASC");
			$not_key_companies = $supplier->toArray2 ( $supplier, null, "\$row->supplier_code - \$row->supplier_name" );
			$key_companies = $supplier->toArray2 ( $supplier, "\$row->supplier_code - \$row->supplier_name", "\$row->supplier_code - \$row->supplier_name" );
		}
		else
		{
			$customer = new Admin_Model_Customer ();
			$customers = $customer->fetchAllBase (null,"customer_code ASC");
			$not_key_companies = $customer->toArray2 ( $customers, null, "\$row->customer_code - \$row->customer_name" );
			$key_companies = $customer->toArray2 ( $customers, "\$row->customer_code - \$row->customer_name", "\$row->customer_code - \$row->customer_name" );
		}
		$form->inbound_company_code->setJQueryParams ( array ('source' => $not_key_companies ) );
		
		//select lý do nhập kho
		$reason = new Admin_Model_Reason ();
		$where = " reason_inbound_type='{$this->inbound_type}' AND reason_warehouse_group_code='{$this->inbound_warehouse_group_code}' ";
		$reasons = $reason->fetchAllBase ( $where, "reason_content ASC" );
		$form->inbound_reason_code->setMultiOptions ( array ('' => '- Chọn -' ) + $reason->toArray2 ( $reasons, "reason_code", '$row->reason_code - $row->reason_content' ) );
		
		//select hàng hóa: NVL/BB
		$product = new Admin_Model_Product ();
		$products = $product->fetchAllBase ( " product_warehouse_group_code='{$this->inbound_warehouse_group_code}' ", 'product_code ASC' );
		$form->inbound_detail_product_code->setMultiOptions ( array ('' => '- Chọn -' ) + $product->toArray2 ( $products, "product_code", '$row->product_code - $row->product_name' ) );
		$form->inbound_detail_product_code->setLabel ( ucfirst ( $this->string_warehouse_group_name ) );
		
		//select thành phẩm
		$products_tp = $product->fetchAllBase ( " product_warehouse_group_code='TP' ", 'product_code ASC' );
		$form->inbound_detail_sub_product_code->setMultiOptions ( array ('' => '- Chọn -' ) + $product->toArray2 ( $products_tp, "product_code", '$row->product_code - $row->product_name' ) );
		$form->inbound_detail_sub_product_code->setLabel ( "Thành phẩm" );
		
		/*
		//select nhóm hàng hóa		
		$product_group = new Admin_Model_ProductGroup ();
		$product_groups = $product_group->fetchAllBase ( null, 'product_group_code ASC' );
		$product_groups = array ('' => '- Chọn -' ) + $product_group->toArray2 ( $product_groups, "product_group_code", "product_group_name" );
		$form->product_group_code->setMultiOptions ( $product_groups );
		$form->product_group_code->setLabel ( "Nhóm " . $this->string_warehouse_group_name );
		*/
		
		//select nhóm hàng hóa
		$product_group = new Admin_Model_ProductGroup ();
		$product_groups = $product_group->fetchOptions ( $product_group->fetchGroups ( '', '', " AND product_group_warehouse_group_code='{$this->inbound_warehouse_group_code}'" ) );
		$form->product_group_code->setMultiOptions ( array ('' => '- Chọn -' ) + $product_groups );
		$form->product_group_code->setLabel ( "Nhóm " . $this->string_warehouse_group_name );
		
		//các cột cần lấy dữ liệu
		$select = " 
		SELECT
			`inbound_id`
			, `inbound_code`
			-- , `inbound_type`
			, `inbound_note`
			, `inbound_company_code`
			, `inbound_create_time`
			, `inbound_create_user`
			-- , `inbound_warehouse_keep_user`
			-- , `inbound_delivery_user`
			-- , `inbound_order_code`
			, `inbound_warehouse_code`
			, `inbound_status`
			, `inbound_order`
			, `warehouse_name`
			, `account_fullname` 
			, (CASE inbound_type WHEN 0 THEN supplier_name ELSE customer_name END) AS company_name";
		if ($report_type == 1)
		{
			$select .= " 
			, `product_name`
			, `unit_name` 
			, inbound_detail_product_quantity
			, inbound_detail_product_code";
		}
		else if ($report_type == 2)
		{
			$select .= " 
			, `product_name`
			, `unit_name` 
			, inbound_detail_product_quantity
			, inbound_detail_product_code
			, reason_content 
			, `inbound_reason_code` 
			, inbound_detail_lot_code
			, inbound_detail_product_time 
			, inbound_detail_expire_time 
			, inbound_detail_note";
		}
		$select .= " FROM tbl_inbound ";
		if ($report_type == 1)
		{
			$select .= " LEFT JOIN tbl_inbound_detail ON inbound_detail_inbound_code=inbound_code 
			LEFT JOIN tbl_product ON inbound_detail_product_code=product_code 
			LEFT JOIN tbl_unit ON inbound_detail_product_unit_code=unit_code ";
		}
		else if ($report_type == 2)
		{
			$select .= " LEFT JOIN tbl_inbound_detail ON inbound_detail_inbound_code=inbound_code 
			LEFT JOIN tbl_product ON inbound_detail_product_code=product_code 
			LEFT JOIN tbl_unit ON inbound_detail_product_unit_code=unit_code 
			LEFT JOIN tbl_reason ON reason_code=inbound_reason_code ";
		}
		$select .= " LEFT JOIN tbl_warehouse ON inbound_warehouse_code=warehouse_code
		LEFT JOIN tbl_account ON inbound_create_user=account_username
		LEFT JOIN tbl_customer ON inbound_company_code=customer_code
		LEFT JOIN tbl_supplier ON inbound_company_code=supplier_code";
		
		//thiết lập điều kiện lấy dữ liệu
		$where = " WHERE inbound_type='{$this->inbound_type}' AND inbound_warehouse_group_code='{$this->inbound_warehouse_group_code}'";
		if ($adminAction != '')
		{
			$form->isValid ( $request->getParams () );
			
			//mã phiếu
			if ($inbound_code != '')
				$where .= " AND `inbound_code` LIKE '%$inbound_code%' ";
			
		//thời gian tao phiếu		
			if ($inbound_create_time_a != "")
			{
				$first_time = $this->_helper->time->first ( $inbound_create_time_a );
				$where .= " AND `inbound_create_time` >= $first_time ";
			}
			if ($inbound_create_time_b != "")
			{
				$last_time = $this->_helper->time->last ( $inbound_create_time_b );
				$where .= " AND `inbound_create_time` <= $last_time ";
			}
			
			//nguoi lap phieu
			if ($inbound_create_user != '')
				$where .= " AND `inbound_create_user` = '$inbound_create_user' ";
			
		//nhom hang hoa
			if ($product_group_code != "")
				$select .= " INNER JOIN tbl_product_group ON (product_product_group_code=product_group_code AND product_group_code='$product_group_code') ";
			
		//hàng hóa
			if ($inbound_detail_product_code != "")
				$where .= " AND `inbound_detail_product_code` = '$inbound_detail_product_code' ";
			
		//thành phẩm
			if ($inbound_detail_sub_product_code != "")
				$where .= " AND `inbound_detail_sub_product_code` = '$inbound_detail_sub_product_code' ";
			
		//kho nhập hàng
			if ($inbound_warehouse_code != '')
				$where .= " AND `inbound_warehouse_code` = '$inbound_warehouse_code' ";
			
		//lí do nhập 
			if ($inbound_reason_code != '')
				$where .= " AND `inbound_reason_code` = '$inbound_reason_code' ";
			
		//đơn vị giao hàng
			if ($inbound_company_code != "")
			{
				$inbound_company_code = explode ( " - ", $inbound_company_code );
				$inbound_company_code = $inbound_company_code [0];
				$where .= " AND `inbound_company_code` = '$inbound_company_code' ";
			}
		}
		
		//thiết lập thứ tự lấy dữ liệu
		$order = $this->_helper->common->getOrderString ( array ('inbound_create_time DESC' ) );
		
		//lấy dữ liệu
		$query = $select . $where . $order;
		$data = $this->_object->queryBase ( $query );
		//phân trang
		$data = $this->_helper->common->paginate ( $data );
		
		///////////////////////////////////////////////////	
		//Kiem tra xem phai truong hop xuat du lieu excel//
		/////////////////////////////////////////////////// 
		if ($request->isPost () && ($layout != ''))
		{
			$tmp_data = array ('type' => "inbound-report-type-" . $report_type, 'inbound_type' => $this->inbound_type, 'string_inbound_type' => $this->string_inbound_type, 'string_inbound_type_2' => $this->string_inbound_type_2, 'inbound_warehouse_group_code' => $this->inbound_warehouse_group_code, 'paginator' => $data, 'from_time' => $inbound_create_time_a, 'to_time' => $inbound_create_time_b );
			return $this->_forward ( 'report', 'index', 'report', $tmp_data );
		}
		
		//truyền dữ liệu ra view
		$this->view->form = $form;
		$this->view->key_companies = $key_companies;
		$this->view->report_type = $report_type;
	}

	//kích hoạt/ vô hiệu hóa 1 hoặc nhiều dòng
	/*public function publishAction()
	{
		$this->_helper->action->publish ( $this->_object, 'inbound_status' );
	}*/
	
	//lưu thứ tự sắp xếp của các dòng
	/*public function saveOrderAction()
	{
		$this->_helper->action->saveOrder ( $this->_object, 'inbound_order' );
	}*/
	
	//xóa 1 hoặc nhiều dòng
	/*public function deleteAction()
	{
		$this->_helper->action->delete ( $this->_object, 'afterDelete', 'beforeDelete' );
	}*/
	
	//hàm kiểm tra dữ liệu ràng buộc trước khi xóa
	//nếu trả về true thì cho xóa, ngược lại kg cho xóa
	public function beforeDelete()
	{
		return true;
	}

	//hàm giải phóng dữ liệu liên quan sau khi xóa
	public function afterDelete()
	{
	
	}

	//thêm phiếu nhập kho.
	public function insertInAction()
	{
		//lấy tham số
		$request = $this->_request;
		
		//Them loai phieu nhap...
		$this->_setInboundString ( $request->getParam ( 'inbound_warehouse_group_code' ), 0 );
		
		//tạo form
		$form = new Inbound_Form_Inbound_Insert ( $this );
		
		//select lý do nhập kho
		/*$reason = new Admin_Model_Reason ();
		$sql = "
		SELECT * 
		FROM view_reason 
		WHERE 
			reason_inbound_type = '{$this->inbound_type}' 
			AND reason_warehouse_group_code = '{$this->inbound_warehouse_group_code}'";
		$reasons = $reason->queryBase ( $sql );
		$not_reasons = $reason->toArray2 ( $reasons, null, "\$row->reason_code - \$row->reason_content" );
		$form->inbound_reason_code->setJQueryParams ( array ('source' => $not_reasons ) );
		$not_reasons_2 = $reason->toArray2 ( $reasons, "\$row->reason_code - \$row->reason_content", "reason_use_company" );
		$form->inbound_reason_code_2->setMultiOptions ( array ('' => '- Chọn -' ) + $not_reasons_2 );*/
		
		//select kho nhập hàng
		/*$warehouse = new Admin_Model_Warehouse ();
		$sql = "
		SELECT * 
		FROM view_warehouse
		ORDER BY warehouse_name ASC";
		$warehouses = $warehouse->queryBase ( $sql );
		$warehouses = $warehouse->toArray2 ( $warehouses, 'warehouse_code', 'warehouse_name' );
		$form->inbound_warehouse_code->setMultiOptions ( array ('' => '- Chọn -' ) + $warehouses );*/
		
		//Lay thong tin thủ kho
		/*$account = new Admin_Model_Account ();
		$accounts = $account->fetchAllBase ( NULL, 'account_fullname ASC' );
		$accounts = $account->toArray2 ( $accounts, 'account_username', 'account_fullname' );
		$form->inbound_warehouse_keep_user->setMultiOptions ( array ('' => '- Chọn -' ) + $accounts );*/
		
		//Lay thong tin ncc
		/*$supplier = new Admin_Model_Supplier ();
		$suppliers = $supplier->fetchAllBase ( NULL, 'supplier_code ASC' );
		$not_key_companies = $supplier->toArray2 ( $suppliers, null, "\$row->supplier_code - \$row->supplier_name" );
		$form->inbound_company_code->setJQueryParams ( array ('source' => $not_key_companies ) );*/
		
		//lay ma phieu
		$max_inbound_code = $this->_object->fetchInboundCode ( $this->inbound_type, $this->inbound_warehouse_group_code );
		$form->inbound_code->setValue ( $max_inbound_code );
		
		//loai phieu
		$warehouse_group = new Admin_Model_WarehouseGroup ();
		//$warehouse_group_name = $warehouse_group->fetchOneBase ( "warehouse_group_name", "warehouse_group_code='$this->inbound_warehouse_group_code'" );
		$form->inbound_type->setValue ( "Nhập kho " . $warehouse_group_name );
		
		//ngày tao phieu
		$form->inbound_create_time->setValue ( $this->_helper->format->time (time()) );
		
		//nguoi tao phieu
		$form->inbound_create_user->setValue ( Zend_Registry::get ( "auth" )->account_fullname );
		
		//Lay don vi tinh
		$unit = new Admin_Model_Unit ();
		$sql = "
		SELECT * 
		FROM view_unit 
		ORDER BY unit_name ASC";
		$units = $unit->queryBase ( $sql );
		
		//Lay thong tin ma hang hoa ho tro autocomplete
		$product = new Admin_Model_Product ();
		$sql = "
		SELECT * 
		FROM view_product 
		WHERE product_warehouse_group_code='{$this->inbound_warehouse_group_code}' 
		ORDER BY product_code ASC ";
		$products = $product->queryBase ( $sql );
		$products = $product->toArray2 ( $products, 'product_code', 'product_name' );
		
		//phần xử lí chính
		if ($request->isPost ()) //khi post giá trị
		{
			$postValues = $request->getPost ();
			$form->inbound_company_code->setRequired ( false );
			
			if ($form->isValid ( $postValues )) //khi giá trị trong form đã được kiểm tra thành công
			{
				$adminAction = $form->getValue ( 'adminAction' );
				
				//kiểm tra có trùng code không?
				if ($this->_object->isExist ( 'inbound_code', $form->inbound_code->getValue () ))
					$form->inbound_code->setValue ( $this->_object->fetchInboundCode ( $this->inbound_type, $this->inbound_warehouse_group_code ) );
				
				//phieu chinh
				$inbound = new Admin_Model_Inbound ( $form->getValues () );
				$inbound->inbound_type = $this->inbound_type; //Loai phieu...
				$inbound->inbound_warehouse_group_code = $this->inbound_warehouse_group_code; //
				$inbound->inbound_create_user = Zend_Registry::get ( 'auth' )->account_username;
				$inbound->inbound_create_time=time();				
				
				//li do nhap xuat kho
				$inbound_reason_code = $inbound->inbound_reason_code;
				$inbound_reason_code = explode ( " - ", $inbound_reason_code );
				$inbound->inbound_reason_code = $inbound_reason_code [0];
				if ($not_reasons_2 [$form->getValue ( 'inbound_reason_code_2' )] != 1)
					$inbound->inbound_company_code = '';
				
				//Đơn vị giao hàng
				$inbound_company_code = $inbound->inbound_company_code;
				$inbound_company_code = explode ( " - ", $inbound_company_code );
				$inbound->inbound_company_code = $inbound_company_code [0];
				
				//Lay thong tin inbound_detail dang mang POST sang mang cac doi tuong Model...
				$inbound_details = array ();
				foreach ( ( array ) $postValues ['inbound_detail_product_code'] as $key => $value )
				{
					$inbound_detail = new Admin_Model_InboundDetail ();
					$inbound_detail->inbound_detail_product_code = $postValues ['inbound_detail_product_code'] [$key];
					$inbound_detail->inbound_detail_product_unit_code = $postValues ['inbound_detail_product_unit_code'] [$key];
					$inbound_detail->inbound_detail_product_quantity = $postValues ['inbound_detail_product_quantity'] [$key];
					$inbound_detail->inbound_detail_location_code = $postValues ['inbound_detail_location_code'] [$key];
					$inbound_detail->inbound_detail_product_time = $postValues ['inbound_detail_product_time'] [$key];
					$inbound_detail->inbound_detail_expire_time = $postValues ['inbound_detail_expire_time'] [$key];
					$inbound_detail->inbound_detail_lot_code = $postValues ['inbound_detail_lot_code'] [$key];
					$inbound_detail->inbound_detail_note = $postValues ['inbound_detail_note'] [$key];
					$inbound_detail->inbound_detail_sub_product_code = $postValues ['inbound_detail_sub_product_code'] [$key];
					$inbound_details [] = $inbound_detail;
				}
				
				//kiểm tra số dòng in ra <= 20 dòng
				/*$row_count = $inbound_detail->countPrintRow ( $inbound_details );
				if ($row_count > 20)
				{
					$form->getElement ( 'inbound_order_code' )->addError ( 'Số dòng khi in phiếu vượt quá 20 dòng. Vui lòng điều chỉnh lại!' );
					$form->markAsError ();
				}*/
				
				//$form->markAsError();
				if (! $form->isErrors ())
				{
					try
					{
						$inbound->insertBase ();
						
						//Thuc hien them chi tiet phieu...
						foreach ( $inbound_details as $inbound_detail )
						{
							$inbound_detail->inbound_detail_inbound_code = $inbound->inbound_code;
							$inbound_detail->insertBase ();
							
							//Thuc hien them inventory
							$inventory = new Admin_Model_Inventory ();
							$where = "inventory_product_code = '{$inbound_detail->inbound_detail_product_code}' 
							AND inventory_location_code = '{$inbound_detail->inbound_detail_location_code}' 
							AND inventory_lot_code = '{$inbound_detail->inbound_detail_lot_code}' 
							-- AND inventory_expire_time = '{$inbound_detail->inbound_detail_expire_time}'
							AND inventory_product_unit_code = '{$inbound_detail->inbound_detail_product_unit_code}' ";
							$inventorys = $inventory->fetchAllBase ( $where, NULL, 1 );
							
							//Truong hop da ton tai -> thuc hien cap nhat...
							if (count ( $inventorys ) > 0)
							{
								$inventory = $inventorys [0];
								$inventory->inventory_quantity += ( int ) $inbound_detail->inbound_detail_product_quantity;
								$inventory->updateBase ();
							}
							else //Truong hop chua ton tai -> thuc hien them moi...
							{
								$inventory = new Admin_Model_Inventory ();
								$inventory->inventory_product_code = $inbound_detail->inbound_detail_product_code;
								$inventory->inventory_product_unit_code = $inbound_detail->inbound_detail_product_unit_code;
								$inventory->inventory_quantity = $inbound_detail->inbound_detail_product_quantity;
								$inventory->inventory_lot_code = $inbound_detail->inbound_detail_lot_code;
								$inventory->inventory_product_time = $inbound_detail->inbound_detail_product_time;
								$inventory->inventory_expire_time = $inbound_detail->inbound_detail_expire_time;
								$inventory->inventory_location_code = $inbound_detail->inbound_detail_location_code;
								$inventory->insertBase ();
							}
						}
						
						//thông báo + chuyển hướng trang khi thành công				
						$this->_helper->flashMessenger ( "Thêm thành công phiếu mới với mã phiếu: <span class='red'>{$inbound->inbound_code}</span>" );
						if ($adminAction == 'save-and-close')
						{
							$this->_helper->redirector ( 'index', 'index', 'inbound', array () );
						}
						else if ($adminAction == 'apply')
						{
							$this->_helper->redirector ( 'detail', 'index', 'inbound', array ('id' => $inbound->inbound_id ) );
						}
						else if ($adminAction == 'save-and-new')
						{
							$this->_helper->redirector ( 'insert-in', 'index', 'inbound', array ('inbound_warehouse_group_code' => $this->inbound_warehouse_group_code ) );
						}
					}
					catch ( Exception $e )
					{
						echo $e->getMessage ();
					}
				}
			}
		}
		else //khi vào form lần đầu tiên
		{
			//kiểm tra phải copy không, nếu phải thì đổ dữ liệu vào
			//$form->inbound_warehouse_code->setValue ( $request->getParam ( 'inbound_warehouse_code' ) );
			//$form->inbound_warehouse_keep_user->setValue ( $request->getParam ( 'inbound_warehouse_keep_user' ) );
			//$form->inbound_reason_code->setValue ( $request->getParam ( 'inbound_reason_code' ) );
			$form->inbound_note->setValue ( $request->getParam ( 'inbound_note' ) );
			//$form->inbound_company_code->setValue ( $request->getParam ( 'inbound_company_code' ) );
			//$form->inbound_delivery_user->setValue ( $request->getParam ( 'inbound_delivery_user' ) );
		}
		
		//Load CSS/JS files...
		$this->view->headScript ()->appendFile ( JS . 'jquery/js/jquery-ui.custom.min.js' );
		$this->view->headLink ()->appendStylesheet ( JS . 'jquery/css/smoothness/jquery-ui.custom.css' );
		$this->view->headLink ()->appendStylesheet ( CSS . 'admin/inbound.css' );
		
		//truyền dữ liệu ra view
		$this->view->form = $form;
		$this->view->units = $units;
		$this->view->products = $products;
		$this->view->inbound_details = $inbound_details;
	}

	//thêm phiếu xuất kho.
	public function insertOutAction()
	{
		//lấy tham số
		$request = $this->_request;
		
		//Them loai phieu nhap...
		$this->_setInboundString ( $request->getParam ( 'inbound_warehouse_group_code' ), 1 );
		
		//tạo form
		$form = new Inbound_Form_Inbound_Insert ( $this );
		
		//select lý do nhập kho
		/*$reason = new Admin_Model_Reason ();
		$sql = "
		SELECT * 
		FROM view_reason 
		WHERE 
			reason_inbound_type = '{$this->inbound_type}' 
			AND reason_warehouse_group_code = '{$this->inbound_warehouse_group_code}'
		";
		$reasons = $reason->queryBase ( $sql );
		$not_reasons = $reason->toArray2 ( $reasons, null, "\$row->reason_code - \$row->reason_content" );
		$form->inbound_reason_code->setJQueryParams ( array ('source' => $not_reasons ) );
		$not_reasons_2 = $reason->toArray2 ( $reasons, "\$row->reason_code - \$row->reason_content", "reason_use_company" );
		$form->inbound_reason_code_2->setMultiOptions ( array ('' => '- Chọn -' ) + $not_reasons_2 );*/
		
		//select kho nhập hàng
		/*$warehouse = new Admin_Model_Warehouse ();
		$sql = "
		SELECT * 
		FROM view_warehouse
		ORDER BY warehouse_name ASC";
		$warehouses = $warehouse->queryBase ( $sql );
		$warehouses = $warehouse->toArray2 ( $warehouses, 'warehouse_code', 'warehouse_name' );
		$form->inbound_warehouse_code->setMultiOptions ( array ('' => '- Chọn -' ) + $warehouses );*/
		
		//Lay thong tin thủ kho
		/*$account = new Admin_Model_Account ();
		$sql = "
		SELECT * 
		FROM view_account
		ORDER BY account_fullname ASC";
		$accounts = $account->queryBase ( $sql );
		$accounts = $account->toArray2 ( $accounts, 'account_username', 'account_fullname' );
		$form->inbound_warehouse_keep_user->setMultiOptions ( array ('' => '- Chọn -' ) + $accounts );*/
		
		//Lay thong tin khach hàng
		$customer = new Admin_Model_Customer ();
		$customers = $customer->fetchAllBase (null,"customer_code ASC");
		$not_key_companies = $customer->toArray2 ( $customers, null, "\$row->customer_code - \$row->customer_name" );
		$form->inbound_company_code->setJQueryParams ( array ('source' => $not_key_companies ) );
		
		//lay ma phieu
		$max_inbound_code = $this->_object->fetchInboundCode ( $this->inbound_type, $this->inbound_warehouse_group_code );
		$form->inbound_code->setValue ( $max_inbound_code );
		
		//loai phieu
		$warehouse_group = new Admin_Model_WarehouseGroup ();
		$warehouse_group_name = $warehouse_group->fetchOneBase ( "warehouse_group_name", "warehouse_group_code='$this->inbound_warehouse_group_code'" );
		$form->inbound_type->setValue ( $this->string_inbound_type . " kho " . $warehouse_group_name );
		
		//ngày tao phieu
		$form->inbound_create_time->setValue ( $this->_helper->format->time (time()) );
		
		//nguoi tao phieu
		$form->inbound_create_user->setValue ( Zend_Registry::get ( "auth" )->account_fullname );
		
		//Lay don vi tinh
		$unit = new Admin_Model_Unit ();
		$sql = "
		SELECT * 
		FROM view_unit 
		ORDER BY unit_name ASC";
		$units = $unit->queryBase ( $sql );
		
		//Lay thong tin ma hang hoa ho tro autocomplete
		$select = " 
		SELECT
			product_id AS `inventory_id`
			, `inventory_product_code`
			, `inventory_product_unit_code`
			, '' AS inventory_quantity
			, '' AS `inventory_lot_code`
			, '' AS `inventory_product_time`
			, '' AS `inventory_expire_time`
			, '' AS `inventory_location_code`
			, '' AS `location_name`
			, `product_name`
		FROM 
			view_product LEFT JOIN tbl_inventory ON product_code = inventory_product_code
		WHERE product_warehouse_group_code='{$this->inbound_warehouse_group_code}'
		GROUP BY inventory_product_code
		ORDER BY inventory_product_code ASC 
		";
		$inventory = new Admin_Model_Inventory ();
		$inventorys = $inventory->queryBase ( $select );
		foreach ( $inventorys as $key => $inventory )
		{
			$array_inventorys [$key] = $inventory->toArray ();
			$array_inventorys [$key] ['inventory_product_time'] = date ( 'd.m.Y', $inventory->inventory_product_time );
			$array_inventorys [$key] ['inventory_expire_time'] = date ( 'd.m.Y', $inventory->inventory_expire_time );
			$array_inventorys [$key] ['product_name'] = $inventory->m_Array ['product_name'];
			$array_inventorys [$key] ['location_name'] = $inventory->m_Array ['location_name'];
		}
		
		//Lay thong tin ma hang hoa thanh pham.
		//$product = new Admin_Model_Product ();
		//$products = $product->getDbTable ()->getAdapter ()->fetchCol ( "SELECT product_code FROM view_product WHERE product_warehouse_group_code = 'TP'" );
		

		//lay chi tiet phieu
		if ($request->isPost ()) //khi post giá trị
		{
			$postValues = $request->getPost ();
		}
		else //khi vào form lần đầu tiên
		{
			$postValues = $request->getParams ();
		}
		$inbound_details = array ();
		$string_product_code = '';
		foreach ( ( array ) $postValues ['inbound_detail_product_code'] as $key => $value )
		{
			if ($postValues ['inbound_detail_product_code'] [$key] != "")
			{
				$inbound_detail = new Admin_Model_InboundDetail ();
				$inbound_detail->inbound_detail_product_code = $postValues ['inbound_detail_product_code'] [$key];
				$inbound_detail->inbound_detail_product_unit_code = $postValues ['inbound_detail_product_unit_code'] [$key];
				$inbound_detail->inbound_detail_product_quantity = $postValues ['inbound_detail_product_quantity'] [$key];
				$inbound_detail->inbound_detail_location_code = $postValues ['inbound_detail_location_code'] [$key];
				$inbound_detail->inbound_detail_product_time = $postValues ['inbound_detail_product_time'] [$key];
				$inbound_detail->inbound_detail_expire_time = $postValues ['inbound_detail_expire_time'] [$key];
				$inbound_detail->inbound_detail_lot_code = $postValues ['inbound_detail_lot_code'] [$key];
				$inbound_detail->inbound_detail_note = $postValues ['inbound_detail_note'] [$key];
				$inbound_detail->inbound_detail_sub_product_code = $postValues ['inbound_detail_sub_product_code'] [$key];
				$inbound_details [] = $inbound_detail;
				
				//chuỗi mã sản phẩm
				if ($string_product_code != '')
					$string_product_code .= ",";
				$string_product_code .= "'{$inbound_detail->inbound_detail_product_code}'";
			}
		}
		
		//phần xử lí chính khi post giá trị
		if ($request->isPost ()) //khi post giá trị
		{
			$postValues = $request->getPost ();
			//$form->inbound_company_code->setRequired ( false );
			//$form->inbound_delivery_user->setRequired ( false );
			if ($form->isValid ( $request->getPost () )) //khi giá trị trong form đã được kiểm tra thành công
			{
				$adminAction = $form->getValue ( 'adminAction' );
				
				//kiểm tra có trùng code không, nếu trùng báo lỗi
				if ($this->_object->isExist ( 'inbound_code', $form->inbound_code->getValue () ))
					$form->inbound_code->setValue ( $this->_object->fetchInboundCode ( $this->inbound_type, $this->inbound_warehouse_group_code ) );
				
				//phieu chinh
				$inbound = new Admin_Model_Inbound ( $form->getValues () );
				$inbound->inbound_type = $this->inbound_type; //Loai phieu...
				$inbound->inbound_warehouse_group_code = $this->inbound_warehouse_group_code; //
				$inbound->inbound_create_user = Zend_Registry::get ( 'auth' )->account_username;
				$inbound->inbound_create_time=time();
				
				//li do nhap xuat kho
				$inbound_reason_code = $inbound->inbound_reason_code;
				$inbound_reason_code = explode ( " - ", $inbound_reason_code );
				$inbound->inbound_reason_code = $inbound_reason_code [0];
				if ($not_reasons_2 [$form->getValue ( 'inbound_reason_code_2' )] != 1)
					$inbound->inbound_company_code = '';
				
		//Đơn vị giao hàng
				$inbound_company_code = $inbound->inbound_company_code;
				$inbound_company_code = explode ( " - ", $inbound_company_code );
				$inbound->inbound_company_code = $inbound_company_code [0];
				
				//lấy lượng trong kho ứng với các sản phẩm của phiếu
				$small_array_inventorys = array ();
				$inventorys_no_ex_time = $inventory->fetchAllBase ( "inventory_product_code IN ($string_product_code) AND inventory_expire_time=0" );
				$inventorys_have_ex_time = $inventory->fetchAllBase ( "inventory_product_code IN ($string_product_code) AND inventory_expire_time>0", "inventory_expire_time ASC" );
				$inventorys = array_merge ( $inventorys_have_ex_time, $inventorys_no_ex_time );
				foreach ( $inventorys as $inventory )
					$small_array_inventorys [$inventory->inventory_product_code] [] = $inventory;
				
				//tự phân bổ vào kho theo qui tắc ưu tiên ngày HH gần nhất
				//có 2 tìh huống: sp chưa nhap kho lần nào hoặc sp trong kho kg đủ để xuất thì đòi hỏi lập phiếu tạm
				$final_inbound_details = array ();
				foreach ( $inbound_details as $inbound_detail )
				{
					$inbound_detail_product_code = $inbound_detail->inbound_detail_product_code;
					$first_inbound_detail_product_quantity = $inbound_detail->inbound_detail_product_quantity; //luong xuất cần phân bổ vào kho
					$tmp_inbound_detail_product_quantity = $first_inbound_detail_product_quantity;
					$array_tmp = array ("inbound_detail_inbound_code" => $inbound->inbound_code, "inbound_detail_product_code" => $inbound_detail_product_code, "inbound_detail_product_quantity" => $inbound_detail_product_quantity, "inbound_detail_product_unit_code" => $inbound_detail->inbound_detail_product_unit_code, "inbound_detail_note" => $inbound_detail->inbound_detail_note );
					$total_inventory_product_quantity = 0;
					$break = false;
					if (count ( $small_array_inventorys [$inbound_detail_product_code] ) > 0) //neu sp nay da nhap vao kho
					{
						foreach ( $small_array_inventorys [$inbound_detail_product_code] as $row )
						{
							$inventory_product_quantity = $row->inventory_quantity;
							$inventory_id = $row->inventory_id;
							
							$final_inbound_detail = new Admin_Model_InboundDetail ( $array_tmp );
							$final_inbound_detail->inbound_detail_expire_time = $row->inventory_expire_time;
							$final_inbound_detail->inbound_detail_product_time = $row->inventory_product_time;
							$final_inbound_detail->inbound_detail_location_code = $row->inventory_location_code;
							$final_inbound_detail->inbound_detail_lot_code = $row->inventory_lot_code;
							$final_inbound_detail->m_Array ['inventory_id'] = $inventory_id;
							if ($tmp_inbound_detail_product_quantity <= $inventory_product_quantity) //lượng xuất nhỏ hơn lượng tồn kho mỗi dòng 
							{
								$final_inbound_detail->inbound_detail_product_quantity = $tmp_inbound_detail_product_quantity;
								
								$break = true;
							}
							else //lượng xuất lớn hơn lượng tồn kho mỗi dòng 
							{
								$final_inbound_detail->inbound_detail_product_quantity = $inventory_product_quantity;
							}
							$final_inbound_details [] = $final_inbound_detail;
							if ($break)
							{
								break;
							}
							else
							{
								$total_inventory_product_quantity += $inventory_product_quantity;
								$tmp_inbound_detail_product_quantity -= $final_inbound_detail->inbound_detail_product_quantity;
							}
						}
						if (! $break && $total_inventory_product_quantity < $first_inbound_detail_product_quantity) //khi lượng trong kho không còn đủ để xuất
						{
							$form->markAsError ();
							$form->getElement ( 'inbound_order_code' )->addError ( "Lượng tồn kho không đủ để xuất ($inbound_detail_product_code: $total_inventory_product_quantity<$first_inbound_detail_product_quantity). Vui lòng điều chỉnh lại!" );
							break;
						}
					}
					else //neu sp chua nhap vao kho lan nao
					{
						$form->markAsError ();
						$form->getElement ( 'inbound_order_code' )->addError ( "Hàng hóa chưa nhập vào kho lần nào ($inbound_detail_product_code). Vui lòng điều chỉnh lại!" );
						break;
					}
				}
			
				//kiểm tra số dòng in ra <= 20 dòng
				$row_count = $inbound_detail->countPrintRow ( $final_inbound_details );
				if ($row_count > 20)
				{
					$form->getElement ( 'inbound_order_code' )->addError ( 'Số dòng khi in phiếu vượt quá 20 dòng. Vui lòng điều chỉnh lại!' );
					$form->markAsError ();
				}
				
				//xu lí khi không có lỗi								
				if (! $form->isErrors ())
				{
					try
					{
						//insert phieu
						$inbound->insertBase ();
						
						//Thuc hien them chi tiet phieu...
						foreach ( $final_inbound_details as $inbound_detail )
						{
							/*if (( string ) $inbound_detail->inbound_detail_sub_product_code != '')
							{
								$tmp = explode ( " - ", $inbound_detail->inbound_detail_sub_product_code );
								$inbound_detail->inbound_detail_sub_product_code = $tmp [0];
							}*/
							
							$inbound_detail->insertBase ();
							
							//cap nhat ton kho
							if ($inbound_detail->m_Array ['inventory_id'] != "") //Truong hop da ton tai -> thuc hien cap nhat...
							{
								$sql = "UPDATE tbl_inventory 
								SET inventory_quantity=inventory_quantity-{$inbound_detail->inbound_detail_product_quantity} 
								WHERE inventory_id='{$inbound_detail->m_Array['inventory_id']}' ";
								$inventory->queryBase ( $sql, 1 );
							}
							/*else //Truong hop chua ton tai -> thuc hien them moi...
							{
								$inventory->inventory_product_code = $inbound_detail->inbound_detail_product_code;
								$inventory->inventory_product_unit_code = $inbound_detail->inbound_detail_product_unit_code;
								$inventory->inventory_quantity = - $inbound_detail->inbound_detail_product_quantity;
								$inventory->inventory_lot_code = $inbound_detail->inbound_detail_lot_code;
								$inventory->inventory_product_time = $inbound_detail->inbound_detail_product_time;
								$inventory->inventory_expire_time = $inbound_detail->inbound_detail_expire_time;
								$inventory->inventory_location_code = $inbound_detail->inbound_detail_location_code;
								$inventory->insertBase ();
							}*/
						}
						
						//thông báo + chuyển hướng trang khi thành công				
						$this->_helper->flashMessenger ( "Thêm thành công phiếu mới với mã phiếu: <span class='red'>{$inbound->inbound_code}</span>" );
						if ($adminAction == 'save-and-close')
						{
							$this->_helper->redirector ( 'index', 'index', 'inbound', array () );
						}
						else if ($adminAction == 'apply')
						{
							$this->_helper->redirector ( 'detail', 'index', 'inbound', array ('id' => $inbound->inbound_id ) );
						}
						else if ($adminAction == 'save-and-new')
						{
							$this->_helper->redirector ( 'insert-out', 'index', 'inbound', array ('inbound_warehouse_group_code' => $this->inbound_warehouse_group_code ) );
						}
					}
					catch ( Exception $e )
					{
						echo $e->getMessage ();
					}
				}
			}
		}
		else //khi vào form lần đầu tiên
		{
			//kiểm tra phải copy không, nếu phải thì đổ dữ liệu vào
			//$form->inbound_warehouse_code->setValue ( $request->getParam ( 'inbound_warehouse_code' ) );
			//$form->inbound_warehouse_keep_user->setValue ( $request->getParam ( 'inbound_warehouse_keep_user' ) );
			//$form->inbound_reason_code->setValue ( $request->getParam ( 'inbound_reason_code' ) );
			$form->inbound_note->setValue ( $request->getParam ( 'inbound_note' ) );
			$form->inbound_company_code->setValue ( $request->getParam ( 'inbound_company_code' ) );
			$form->inbound_delivery_user->setValue ( $request->getParam ( 'inbound_delivery_user' ) );
		}
		
		//Load CSS/JS files...
		$this->view->headScript ()->appendFile ( JS . 'jquery/js/jquery-ui.custom.min.js' );
		$this->view->headLink ()->appendStylesheet ( JS . 'jquery/css/smoothness/jquery-ui.custom.css' );
		$this->view->headLink ()->appendStylesheet ( CSS . 'admin/inbound.css' );
		
		//truyền dữ liệu ra view
		$this->view->inbound_warehouse_group_code = $this->inbound_warehouse_group_code;
		$this->view->form = $form;
		$this->view->units = $units;
		$this->view->array_inventorys = $array_inventorys;
		$this->view->inbound_details = $inbound_details;
		$this->view->products = $products;
	}

	//cập nhật phiếu nhập xuất kho.
	public function updateAction()
	{
		//lấy tham số
		$request = $this->_request;
		$id = $request->getParam ( 'id' );
		$tmp = $request->getParam ( 'tmp' );
		
		//lấy phiếu nhập/xuất
		if ($tmp == 1)
			$inbound = new Admin_Model_TmpInbound ();
		else
			$inbound = new Admin_Model_Inbound ();
		$inbound->findBase ( $id );
		
		//lấy chi tiết phiếu
		if ($tmp == 1)
		{
			$module = 'tmp-inbound';
			$inbound_detail = new Admin_Model_TmpInboundDetail ();
		}
		else
		{
			$module = 'inbound';
			$inbound_detail = new Admin_Model_InboundDetail ();
		}
		$query = "
		SELECT 
			inbound_detail_product_code,
			p1.product_name,
			unit_name, 
			inbound_detail_location_code,
			location_name,
			inbound_detail_product_quantity,
			inbound_detail_product_time,
			inbound_detail_expire_time,
			inbound_detail_lot_code,
			inbound_detail_note
		FROM tbl_inbound_detail
			LEFT JOIN tbl_product p1 ON inbound_detail_product_code=p1.product_code
			LEFT JOIN tbl_unit ON inbound_detail_product_unit_code=unit_code
			LEFT JOIN tbl_location ON inbound_detail_location_code=location_code
		WHERE inbound_detail_inbound_code = '{$inbound->inbound_code}' ";
		$inbound_details = $inbound_detail->queryBase ( $query, " inbound_detail_id ASC " );
		
		//them loai phieu nhap, xuất
		$this->_setInboundString ( $inbound->inbound_warehouse_group_code, $inbound->inbound_type );
		
		//tạo form
		$form = new Inbound_Form_Inbound_Insert ( $this );
		
		//select lý do nhập kho
		$reason = new Admin_Model_Reason ();
		$sql = "
		SELECT * 
		FROM view_reason 
		WHERE 
			reason_inbound_type = '{$this->inbound_type}' 
			AND reason_warehouse_group_code = '{$this->inbound_warehouse_group_code}'
		";
		$reasons = $reason->queryBase ( $sql );
		$not_reasons = $reason->toArray2 ( $reasons, null, "\$row->reason_code - \$row->reason_content" );
		$form->inbound_reason_code->setJQueryParams ( array ('source' => $not_reasons ) );
		$not_reasons_2 = $reason->toArray2 ( $reasons, "\$row->reason_code - \$row->reason_content", "reason_use_company" );
		$form->inbound_reason_code_2->setMultiOptions ( array ('' => '- Chọn -' ) + $not_reasons_2 );
		
		//kho nhập hàng
		$warehouse = new Admin_Model_Warehouse ();
		$warehouse_name = $warehouse->fetchOneBase ( "warehouse_name", "warehouse_code='{$first_inbound->inbound_warehouse_code}'" );
		$form->inbound_warehouse_code->setIgnore ( true )->setRequired ( false );
		
		//Lay thong tin thủ kho
		$account = new Admin_Model_Account ();
		$account = new Admin_Model_Account ();
		$sql = "
		SELECT * 
		FROM view_account
		ORDER BY account_fullname ASC";
		$accounts = $account->queryBase ( $sql );
		$accounts = $account->toArray2 ( $accounts, 'account_username', 'account_fullname' );
		$form->inbound_warehouse_keep_user->setMultiOptions ( array ('' => '- Chọn -' ) + $accounts );
		
		//Lay thong tin ncc, khach hàng
		if ($this->inbound_type == '0')
		{
			$supplier = new Admin_Model_Supplier ();
			$suppliers = $supplier->fetchAllBase (null,"supplier_code ASC");
			$not_key_companies = $supplier->toArray2 ( $suppliers, null, "\$row->supplier_code - \$row->supplier_name" );
		}
		else
		{
			$customer = new Admin_Model_Customer ();
			$customers = $customer->fetchAllBase (null,"customer_code ASC");
			$not_key_companies = $customer->toArray2 ( $customers, null, "\$row->customer_code - \$row->customer_name" );
		}
		$form->inbound_company_code->setJQueryParams ( array ('source' => $not_key_companies ) );
		
		//loai phieu
		$warehouse_group = new Admin_Model_WarehouseGroup ();
		$warehouse_group_name = $warehouse_group->fetchOneBase ( "warehouse_group_name", "warehouse_group_code='$this->inbound_warehouse_group_code'" );
		$form->inbound_type->setValue ( $this->string_inbound_type . " kho " . $warehouse_group_name );
		
		//ngày tao phieu
		$form->inbound_create_time->setValue ( $this->_helper->format->time ( $inbound->inbound_create_time ) );
		
		//Lay don vi tinh
		/*$unit = new Admin_Model_Unit ();
		$sql = "
		SELECT * 
		FROM view_unit 
		ORDER BY unit_name ASC";
		$units = $unit->queryBase ( $sql );*/
		
		//Lay thong tin ma hang hoa ho tro autocomplete
		/*$product = new Admin_Model_Product ();
		$sql = "
		SELECT * 
		FROM view_product 
		WHERE product_warehouse_group_code='{$this->inbound_warehouse_group_code}' ";
		$products = $product->queryBase ( $sql );
		$products = $product->toArray2 ( $products, 'product_code', 'product_name' );*/
		
		//Lay thong tin ma TP ho tro autocomplete
		//$tp_products = $product->getDbTable ()->getAdapter ()->fetchCol ( "SELECT product_code FROM view_product WHERE product_warehouse_group_code = 'TP'" );
		

		//phần xử lí chính
		if ($request->isPost ()) //khi post giá trị
		{
			$postValues = $request->getPost ();
			$form->inbound_company_code->setRequired ( false );
			if ($form->isValid ( $postValues )) //khi giá trị trong form đã được kiểm tra thành công
			{
				$adminAction = $form->getValue ( 'adminAction' );
				if ($tmp == 1)
					$update_inbound = new Admin_Model_TmpInbound ( $form->getValues () );
				else
					$update_inbound = new Admin_Model_Inbound ( $form->getValues () );
				
		//li do nhap xuat kho
				$inbound_reason_code = $update_inbound->inbound_reason_code;
				$inbound_reason_code = explode ( " - ", $inbound_reason_code );
				$update_inbound->inbound_reason_code = $inbound_reason_code [0];
				if ($not_reasons_2 [$form->getValue ( 'inbound_reason_code_2' )] != 1)
					$update_inbound->inbound_company_code = '';
				
		//Đơn vị giao hàng
				$inbound_company_code = $update_inbound->inbound_company_code;
				$inbound_company_code = explode ( " - ", $inbound_company_code );
				$update_inbound->inbound_company_code = $inbound_company_code [0];
				
				//Lay thong tin inbound_detail dang mang POST sang mang cac doi tuong Model...
				/*$inbound_details = array ();
				foreach ( ( array ) $postValues ['inbound_detail_product_code'] as $key => $value )
				{
					$inbound_detail = new Admin_Model_InboundDetail ();
					$inbound_detail->inbound_detail_product_code = $postValues ['inbound_detail_product_code'] [$key];
					$inbound_detail->inbound_detail_product_unit_code = $postValues ['inbound_detail_product_unit_code'] [$key];
					$inbound_detail->inbound_detail_product_quantity = $postValues ['inbound_detail_product_quantity'] [$key];
					$inbound_detail->inbound_detail_location_code = $postValues ['inbound_detail_location_code'] [$key];
					$inbound_detail->inbound_detail_product_time = $postValues ['inbound_detail_product_time'] [$key];
					$inbound_detail->inbound_detail_expire_time = $postValues ['inbound_detail_expire_time'] [$key];
					$inbound_detail->inbound_detail_lot_code = $postValues ['inbound_detail_lot_code'] [$key];
					$inbound_detail->inbound_detail_note = $postValues ['inbound_detail_note'] [$key];
					$inbound_detail->inbound_detail_sub_product_code = $postValues ['inbound_detail_sub_product_code'] [$key];
					$inbound_details [] = $inbound_detail;
				}*/
				
				//kiểm tra có trùng code không, nếu trùng báo lỗi
				if ($this->_object->isExist ( 'inbound_code', $inbound->inbound_code ))
				{
					//$form->getElement ( 'inbound_code' )->addError ( $this->_helper->common->getCaption ( 'inbound_code' ) . ' đã tồn tại.' );
					$form->inbound_code->setValue ( $this->_object->fetchInboundCode ( $this->inbound_type, $this->inbound_warehouse_group_code ) );
				}
				
				//$form->markAsError();
				if (! $form->isErrors ())
				{
					try
					{
						//cap nhật dòng mới
						$update_inbound->updateBase ( $id );
						
						//lấy log
						$array_update_inbound = $update_inbound->toArray ();
						$array_inbound = $inbound->toArray ();
						$inbound_log_note = "Lí do cập nhật: " . $request->getParam ( 'inbound_log_note' );
						$not_log_array = array ("inbound_id", "inbound_type", "inbound_warehouse_group_code", "inbound_status", "inbound_order" );
						foreach ( $array_inbound as $key => $old_value )
						{
							$new_value = $array_update_inbound [$key];
							if ($new_value != $old_value && array_search ( $key, $not_log_array ) === false)
							{
								$caption = $this->_helper->common->getCaption ( $key );
								$inbound_log_note .= "<br/>$caption: [$old_value] => [$new_value]";
							}
						}
						
						//thêm log vào
						$inbound_log = new Admin_Model_InboundLog ();
						$inbound_log->inbound_log_create_user = Zend_Registry::get ( "auth" )->account_username;
						$inbound_log->inbound_log_create_time = time ();
						$inbound_log->inbound_log_note = $inbound_log_note;
						$inbound_log->inbound_log_inbound_code = $inbound->inbound_code;
						$inbound_log->insertBase ();
						
						//xóa chi tiết phiếu cũ
						/*$inbound_detail = new Admin_Model_InboundDetail ();
						$inbound_detail->inbound_detail_inbound_code = '';
						$inbound_detail->inbound_detail_inbound_log_id = $inbound_log->inbound_log_id;
						$inbound_detail->updateAllBase ( "inbound_detail_inbound_code='{$inbound->inbound_code}'" );
						
						//Thuc hien them chi tiet phieu...
						foreach ( $inbound_details as $inbound_detail )
						{
							if (( string ) $inbound_detail->inbound_detail_sub_product_code != '')
							{
								$tmp = explode ( " - ", $inbound_detail->inbound_detail_sub_product_code );
								$inbound_detail->inbound_detail_sub_product_code = $tmp [0];
							}
							$inbound_detail->inbound_detail_inbound_code = $inbound->inbound_code;
							$inbound_detail->insertBase ();
						}*/
						
						//thông báo + chuyển hướng trang khi thành công				
						$this->_helper->flashMessenger ( "Cập nhật thành công phiếu với mã phiếu: <span class='red'>{$inbound->inbound_code}</span>" );
						if ($adminAction == 'save-and-close')
						{
							$this->_helper->redirector ( 'index', 'index', $module, array () );
						}
						else if ($adminAction == 'apply')
						{
							$this->_helper->redirector ( 'detail', 'index', $module, array ('id' => $inbound->inbound_id ) );
						}
						else if ($adminAction == 'save-and-new')
						{
							if ($this->inbound_type == 0)
								$this->_helper->redirector ( 'insert-in', 'index', $module, array ('inbound_warehouse_group_code' => $this->inbound_warehouse_group_code ) );
							else
								$this->_helper->redirector ( 'insert-out', 'index', $module, array ('inbound_warehouse_group_code' => $this->inbound_warehouse_group_code ) );
						}
					}
					catch ( Exception $e )
					{
						echo $e->getMessage ();
					}
				}
			}
		}
		else //khi vào form lần đầu tiên
		{
			$form->inbound_code->setValue ( $inbound->inbound_code );
			$form->inbound_create_user->setValue ( Zend_Registry::get ( "auth" )->account_fullname );
			$form->inbound_warehouse_code->setValue ( $inbound->inbound_warehouse_code );
			$form->inbound_order_code->setValue ( $inbound->inbound_order_code );
			$form->inbound_warehouse_keep_user->setValue ( $inbound->inbound_warehouse_keep_user );
			$form->inbound_reason_code->setValue ( $inbound->inbound_reason_code );
			$form->inbound_note->setValue ( $inbound->inbound_note );
			$form->inbound_company_code->setValue ( $inbound->inbound_company_code );
			$form->inbound_delivery_user->setValue ( $inbound->inbound_delivery_user );
		}
		
		//Load CSS/JS files...
		$this->view->headScript ()->appendFile ( JS . 'jquery/js/jquery-ui.custom.min.js' );
		$this->view->headLink ()->appendStylesheet ( JS . 'jquery/css/smoothness/jquery-ui.custom.css' );
		$this->view->headLink ()->appendStylesheet ( CSS . 'admin/inbound.css' );
		
		//truyền dữ liệu ra view
		$this->view->inbound_warehouse_group_code = $this->inbound_warehouse_group_code;
		$this->view->form = $form;
		$this->view->units = $units;
		$this->view->products = $products;
		$this->view->inbound_details = $inbound_details;
		$this->view->inbound = $inbound;
		$this->view->tp_products = $tp_products;
		$this->view->warehouse_name = $warehouse_name;
		$this->view->s_title = " / <a href='" . $this->view->url ( array ("action" => "index", "inbound_type" => $this->inbound_type, "inbound_warehouse_group_code" => $this->inbound_warehouse_group_code ) ) . "'>" . ($this->inbound_type == "0" ? "Phiếu nhập kho" : "Phiếu xuất kho") . " {$this->inbound_warehouse_group_code}" . "</a> / Cập nhật phiếu: {$inbound->inbound_code}";
	}

	//xem chi tiet 1 dòng
	public function detailAction()
	{
		//lấy tham số
		$request = $this->_request;
		$id = $request->getParam ( 'id' );
		$tmp = $request->getParam ( 'tmp', '' );
		if (is_array ( $id ))
			$id = $id [count ( $id ) - 1];
		
		//lấy đối tượng cần cập nhật
		if ($tmp == '1')
			$first_inbound = new Admin_Model_TmpInbound ();
		else
			$first_inbound = new Admin_Model_Inbound ();
		$first_inbound->findBase ( $id );
		$this->_setInboundString ( $first_inbound->inbound_warehouse_group_code, $first_inbound->inbound_type );
		
		//tạo form
		$form = new Inbound_Form_Inbound_Detail ( $this );
		$form->populate ( $first_inbound->toArray () );
		
		//lay tên li do
		$reason = new Admin_Model_Reason ();
		$reason->fetchRowAllBase ( "reason_code='{$first_inbound->inbound_reason_code}'" );
		$form->inbound_reason_code->setValue ( $reason->reason_content );
		$reason_use_company = $reason->reason_use_company;
		
		//lay kho nhập hàng
		$warehouse = new Admin_Model_Warehouse ();
		$warehouse_name = $warehouse->fetchOneBase ( "warehouse_name", "warehouse_code='{$first_inbound->inbound_warehouse_code}'" );
		$form->inbound_warehouse_code->setValue ( $first_inbound->inbound_warehouse_code . " - " . $warehouse_name );
		
		//Lay thong tin thủ kho
		$account = new Admin_Model_Account ();
		$account_fullname = $account->fetchOneBase ( "account_fullname", "account_username='{$first_inbound->inbound_warehouse_keep_user}'" );
		$form->inbound_warehouse_keep_user->setValue ( $first_inbound->inbound_warehouse_keep_user . " - " . $account_fullname );
		
		//Lay thong tin ncc, khach hàng
		if ($first_inbound->inbound_type == '0')
		{
			$supplier = new Admin_Model_Supplier ();
			$company_name = $supplier->fetchOneBase ( "supplier_name", "supplier_code='$first_inbound->inbound_company_code'" );
		}
		else
		{
			$customer = new Admin_Model_Customer ();
			$company_name = $customer->fetchOneBase ( "customer_name", "customer_code='$first_inbound->inbound_company_code'" );
		}
		$form->inbound_company_code->setValue ( $company_name );
		
		//loai phieu
		$warehouse_group = new Admin_Model_WarehouseGroup ();
		$warehouse_group_name = $warehouse_group->fetchOneBase ( "warehouse_group_name", "warehouse_group_code='{$first_inbound->inbound_warehouse_group_code}'" );
		$form->inbound_type->setValue ( (( string ) $first_inbound->inbound_type == '0' ? "Nhập" : "Xuất") . " kho " . $warehouse_group_name );
		
		//ngay tao phieu
		$form->inbound_create_time->setValue ( $this->_helper->format->time ( $first_inbound->inbound_create_time ) );
		
		//Lay thong tin inbound_detail
		if ($tmp == '1')
		{
			$inbound_detail = new Admin_Model_TmpInboundDetail ();
			$tbl_inbound_detail = 'tbl_tmp_inbound_detail';
		}
		else
		{
			$inbound_detail = new Admin_Model_InboundDetail ();
			$tbl_inbound_detail = 'tbl_inbound_detail';
		}
		$query = "
		SELECT ";
		if ($this->inbound_type == 1 && ($this->inbound_warehouse_group_code == 'NVL' || $this->inbound_warehouse_group_code == 'BB'))
			$query .= "
			p2.product_name AS sub_product_name,
			inbound_detail_sub_product_code, ";
		$query .= "
			inbound_detail_product_code,
			p1.product_name,
			unit_name, 
			inbound_detail_location_code,
			location_name,
			inbound_detail_product_quantity,
			inbound_detail_product_time,
			inbound_detail_expire_time,
			inbound_detail_lot_code,
			inbound_detail_note
		FROM $tbl_inbound_detail ";
		if ($this->inbound_type == 1 && ($this->inbound_warehouse_group_code == 'NVL' || $this->inbound_warehouse_group_code == 'BB'))
			$query .= " LEFT JOIN tbl_product p2 ON inbound_detail_sub_product_code=p2.product_code ";
		$query .= "
			LEFT JOIN tbl_product p1 ON inbound_detail_product_code=p1.product_code
			LEFT JOIN tbl_unit ON inbound_detail_product_unit_code=unit_code
			LEFT JOIN tbl_location ON inbound_detail_location_code=location_code
		WHERE inbound_detail_inbound_code = '{$first_inbound->inbound_code}' ";
		$inbound_details = $inbound_detail->queryBase ( $query, " inbound_detail_id ASC " );
		
		//Load CSS/JS files...
		$this->view->headLink ()->appendStylesheet ( CSS . 'admin/inbound.css' );
		
		//truyền dữ liệu ra view
		$this->view->form = $form;
		$this->view->inbound_details = $inbound_details;
		$this->view->inbound = $first_inbound;
		$this->view->reason_use_company = $reason_use_company;
		$this->view->tmp = $tmp;
		$this->view->inbound_id = $id;
		$this->view->s_title = " / <a href='" . $this->view->url ( array ("action" => "index", "inbound_type" => $this->inbound_type, "inbound_warehouse_group_code" => $this->inbound_warehouse_group_code ) ) . "'>" . ($this->inbound_type == "0" ? "Phiếu nhập kho" : "Phiếu xuất kho") . " {$this->inbound_warehouse_group_code}" . ($tmp == 1 ? " (ghi chú)" : "") . "</a> / Xem chi tiết phiếu: {$first_inbound->inbound_code}";
	}

	//print phiếu nhập xuất kho
	public function printAction()
	{
		//Dung layout ajax
		$this->getHelper ( 'Layout' )->setLayout ( 'print' );
		
		//lấy tham số
		$request = $this->_request;
		$id = $request->getParam ( 'id' );
		$tmp = $request->getParam ( 'tmp', '' );
		if (is_array ( $id ))
			$id = $id [count ( $id ) - 1];
		
		//lấy đối tượng cần cập nhật
		$first_inbound = new Admin_Model_Inbound ();
		if ($tmp == '1')
			$first_inbound = new Admin_Model_TmpInbound ();
		
		$first_inbound->findBase ( $id );
		$this->_setInboundString ( $first_inbound->inbound_warehouse_group_code, $first_inbound->inbound_type );
		
		//lay tên nha cung cap hoac khach hang
		if ($this->inbound_type == '0') //nếu nhập lấy ncc
		{
			$supplier = new Admin_Model_Supplier ();
			$company_name = $supplier->fetchOneBase ( "supplier_name", "supplier_code='{$first_inbound->inbound_company_code}'" );
		}
		else //nguoc lai lay khach hang
		{
			$customer = new Admin_Model_Customer ();
			$company_name = $customer->fetchOneBase ( "customer_name", "customer_code='{$first_inbound->inbound_company_code}'" );
		}
		
		//lay tên li do
		$reason = new Admin_Model_Reason ();
		$reason_content = $reason->fetchOneBase ( "reason_content", "reason_code='{$first_inbound->inbound_reason_code}'" );
		
		//Lay thong tin inbound_detail
		$inbound_detail = new Admin_Model_InboundDetail ();
		$tbl_inbound_detail = 'tbl_inbound_detail';
		if ($tmp == '1')
		{
			$inbound_detail = new Admin_Model_TmpInboundDetail ();
			$tbl_inbound_detail = 'tbl_tmp_inbound_detail';
		}
		$query = "
		SELECT product_name,unit_name, inbound_detail_product_quantity,inbound_detail_lot_code,product_product_group_code,product_group_name,inbound_detail_product_code
		FROM $tbl_inbound_detail 
			LEFT JOIN tbl_product ON inbound_detail_product_code=product_code
			LEFT JOIN tbl_product_group ON product_group_code=product_product_group_code
			LEFT JOIN tbl_unit ON inbound_detail_product_unit_code=unit_code
		WHERE inbound_detail_inbound_code = '{$first_inbound->inbound_code}' 
		ORDER BY product_product_group_code ASC ";
		$inbound_details = $inbound_detail->queryBase ( $query, " inbound_detail_id ASC " );
		
		//truyền dữ liệu ra view
		$this->view->inbound = $first_inbound;
		$this->view->inbound_details = $inbound_details;
		$this->view->company_name = $company_name;
		$this->view->reason_content = $reason_content;
	}
}